package zjc.bookkeeping.fragment.statistics;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dld.view.SegmentedControlItem;
import com.dld.view.SegmentedControlView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.android.material.tabs.TabLayout;
import com.loper7.date_time_picker.DateTimeConfig;
import com.loper7.date_time_picker.DateTimePicker;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import zjc.bookkeeping.R;
import zjc.bookkeeping.db.ConsumptionBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.db.MethodBean;
import zjc.bookkeeping.fragment.tools.MyMarkerView;
import zjc.bookkeeping.fragment.tools.MyPercentFormatter;


public class StatisticsMonthFragment extends Fragment {

    private View fragment_statistics_month;
    private TabLayout tabLayout;
    private String[] months = new String[12];
    private Button year_btn;
    private SegmentedControlView mscv;//收支统计柱形图-收支转换
    private LineChart lineChart; //折线图
    private PieChart chart3; //饼状图
    private ListView report_list;
    private CardView cardView4;
    private CardView cardView3;
    private CardView cardView2;
    private CardView cardView1;
    private TextView month_expend;
    private TextView month_income;
    private TextView month_balance;
    private ScrollView scrollView;

    private int width;
    private int height;

    private float[] month_money = new float[3];//存放月支出 收入 结余
    private String selected_year;// 选中年
    private int selected_month;//选中月
    private SimpleDateFormat dateFormat=new SimpleDateFormat("MM-dd");
    private List<ReportListItemData> list = new ArrayList<>();
    private List<String> consumptionClasses = new ArrayList<>();//消费分类

    DecimalFormat df = new DecimalFormat("#0.00");// 保留两位小数

    private int listviewElementsheight = 0;

    public StatisticsMonthFragment() {
        // Required empty public constructor
    }


    public static StatisticsMonthFragment newInstance(String param1, String param2) {
        StatisticsMonthFragment fragment = new StatisticsMonthFragment();
        return fragment;
    }

    private void list_data_change(int year, int month) {
        list.clear();
        Log.i("clear","数据改变");
        int days_count = getDaysOfMonth(year,month);
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 0);
        for (int i = 1; i <= days_count; i++) {
            calendar.set(Calendar.DAY_OF_MONTH,i);
            String changeDay = dateFormat.format(calendar.getTime());
            float day_spending = DBManager.getDaySumConsumption(year, month, i, 0);
            float day_income = DBManager.getDaySumConsumption(year, month, i, 1);
            // 只显示有数据的记录
            if (day_spending != 0 || day_income != 0) {
                float day_balance = day_income - day_spending;
                list.add(new ReportListItemData(changeDay, day_spending, day_income, day_balance));
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragment_statistics_month = inflater.inflate(R.layout.fragment_statistics_month,container,false);
        //获取屏幕宽度
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;
        initView();
        bindData();
        Adaptation();
        return fragment_statistics_month;
    }

    // 适配处理
    public void Adaptation(){
        //定义布局参数
        //Log.i("width",String.valueOf(width * 0.9));
        //Log.i("height",String.valueOf(height * 0.28));
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.width = (int) (width * 0.9);
        layoutParams.height = (int) (width * 0.9 * 0.25);
        //Log.e("height2", String.valueOf(layoutParams.height));
        layoutParams.topMargin = (int) (width * 0.05);
        layoutParams.leftMargin = (int) (width * 0.05);
        layoutParams.rightMargin = (int) (width * 0.05);
        cardView1.setLayoutParams(layoutParams);

        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams2.height = (int) (width * 0.9 * 0.618);
        layoutParams2.width = (int) (width * 0.9);
        layoutParams2.topMargin = (int) (width * 0.05);
        layoutParams2.leftMargin = (int) (width * 0.05);
        layoutParams2.rightMargin = (int) (width * 0.05);
        cardView2.setLayoutParams(layoutParams2);

        LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams4.height = (int) (width * 0.9 * 0.618);
        layoutParams4.width = (int) (width * 0.9);
        layoutParams4.topMargin = (int) (width * 0.05);
        layoutParams4.leftMargin = (int) (width * 0.05);
        layoutParams4.rightMargin = (int) (width * 0.05);
        cardView4.setLayoutParams(layoutParams4);

        LinearLayout.LayoutParams layoutParams5 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams5.height = (int) (width * 0.9 * 0.8);
        layoutParams5.width = (int) (width * 0.9);
        layoutParams5.topMargin = (int) (width * 0.05);
        layoutParams5.leftMargin = (int) (width * 0.05);
        layoutParams5.rightMargin = (int) (width * 0.05);
        layoutParams5.bottomMargin = (int) (width * 0.08);
        cardView3.setLayoutParams(layoutParams5);



        LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams3.width = (int) (width * 0.75);
        layoutParams3.height = (int) (width * 0.9 * 0.618);
        layoutParams3.topMargin = (int) (-width * 0.05);
        layoutParams3.leftMargin = (int) (width * 0.05);
        layoutParams3.rightMargin = (int) (width * 0.05);
        layoutParams3.bottomMargin = (int) (width * 0.08);
        chart3.setLayoutParams(layoutParams3);
    }

    public void initView(){
        tabLayout = fragment_statistics_month.findViewById(R.id.tab_layout);
        year_btn = fragment_statistics_month.findViewById(R.id.year_btn);
        mscv = fragment_statistics_month.findViewById(R.id.scv);
        lineChart = fragment_statistics_month.findViewById(R.id.chart1);
        cardView4 = fragment_statistics_month.findViewById(R.id.cardview4);
        cardView3 = fragment_statistics_month.findViewById(R.id.cardview3);
        cardView2 = fragment_statistics_month.findViewById(R.id.cardview2);
        cardView1 = fragment_statistics_month.findViewById(R.id.cardview1);
        chart3 = fragment_statistics_month.findViewById(R.id.chart3);
        report_list = fragment_statistics_month.findViewById(R.id.report_list);
        month_expend = fragment_statistics_month.findViewById(R.id.month_expend);
        month_income = fragment_statistics_month.findViewById(R.id.month_income);
        month_balance = fragment_statistics_month.findViewById(R.id.month_balance);
        scrollView = fragment_statistics_month.findViewById(R.id.scrollview);
        report_list.setEmptyView(fragment_statistics_month.findViewById(R.id.empty_view));
        report_list.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    scrollView.requestDisallowInterceptTouchEvent(false);
                }else{
                    scrollView.requestDisallowInterceptTouchEvent(true);//屏蔽父控件的拦截事件
                }
                return false;
            }
        });


        Date date=new Date();
        System.out.println(date);
        System.out.println(dateFormat.format(date));
        final String[] dates = new String[7];
        Date today1 = new Date(System.currentTimeMillis());
        Date date_one = new Date();
        Calendar cal_1=Calendar.getInstance();//获取当前日期
        cal_1.add(Calendar.MONTH, 0);


        Date today = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
        int year = Integer.valueOf(sdf0.format(today));
        int month = Integer.valueOf(sdf1.format(today));
        selected_year = String.valueOf(year);
        selected_month = month;
        chart(year,month,0);//折线图
        pieChart(year,month);

        SimpleDateFormat dateFormat1=new SimpleDateFormat("dd");
        int currentDay = Integer.valueOf(dateFormat1.format(today1));//获取日
        //list.clear();
        for (int i = 1; i <= currentDay; i++){
            cal_1.set(Calendar.DAY_OF_MONTH,i);//修改日期
            String changeDay = dateFormat.format(cal_1.getTime());
            float day_spending = DBManager.getDaySumConsumption(year,month,i,0);
            float day_income = DBManager.getDaySumConsumption(year,month,i,1);
            // 只显示有数据的记录
            if (day_spending != 0 || day_income != 0){
                float day_balance = day_income - day_spending;
                list.add(new ReportListItemData(changeDay,day_spending,day_income,day_balance));
            }

        }




        ReportListAdapter adapter = new ReportListAdapter(getContext(),list);
        report_list.setAdapter(adapter);
        if (adapter.getCount() > 0){
            Log.e("adapter",String.valueOf(list.size()));
            for (int i = 0; i < list.size(); i++) {
                View mView = adapter.getView(0, null, report_list);
                mView.measure(
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                listviewElementsheight += mView.getMeasuredHeight();
                Log.e("monthheight", String.valueOf(mView.getMeasuredHeight()));
            }
            listviewElementsheight = (int) (listviewElementsheight/ (adapter.getCount() + 1) * (adapter.getCount() + 5) * 1.7);
            Log.e("monthheight", String.valueOf(listviewElementsheight));
        }

//        ViewTreeObserver vto = report_list.getViewTreeObserver();
//        // 根据列表高度动态改变报表高度
//        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            public void onGlobalLayout() {
//                int h = report_list.getHeight();
//                ViewGroup.LayoutParams params = cardView3.getLayoutParams();
//                params.height = h ;//300
//                cardView3.setLayoutParams(params);
//               report_list.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//            }
//        });


        switchChange();
        //月份滑动监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tabLayout.getSelectedTabPosition() + 1;
                int cur_month = pos;
                int cur_year = Integer.parseInt((String) year_btn.getText());
                Log.i("点击",String.valueOf(cur_year) + " " + String.valueOf(cur_month));
                month_money[0] = DBManager.getMonthConsumption(cur_year,cur_month,0);//月支出
                month_money[1] = DBManager.getMonthConsumption(cur_year,cur_month,1);//月收入
                month_money[2] = month_money[1] - month_money[0];//月结余
                month_expend.setText(df.format(month_money[0]));
                month_income.setText(df.format(month_money[1]));
                month_balance.setText(df.format(month_money[2]));
                chart(cur_year,cur_month,mscv.getSelectedItem());
                list_data_change(cur_year,cur_month);
                pieChart(cur_year,cur_month);
                lineChart.highlightValue(null);
                adapter.notifyDataSetChanged();//更新数据
                MyMarkerView mv = new MyMarkerView(getContext(), R.layout.custom_marker_view,String.valueOf(cur_year),cur_month);

                // Set the marker to the chart
                mv.setChartView(lineChart);
                lineChart.setMarker(mv);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        Calendar calendar = Calendar.getInstance();
        calendar.set(2000, 1, 1, 0, 0, 0);

        year_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(
                                DateTimeConfig.YEAR,//显示年
                                DateTimeConfig.MONTH//显示月
                        )
                        .setMinTime(calendar.getTimeInMillis())//设置最远时间为2000-1-1-0-0-0
                        .showFocusDateInfo(false)
                        .setTitle("选择月份")
                        .showBackNow(false)
                        .setOnChoose("确定", aLong -> {
                            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateStr = dateformat.format(aLong);
                            selected_year = dateStr.substring(0,4);
                            selected_month = Integer.parseInt(dateStr.substring(5,7));
                            year_btn.setText(selected_year);//年份切换

                            tabLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    tabLayout.getTabAt(selected_month-1).select();
                                    //Log.i("月份",String.valueOf(selected_month));
                                    month_money[0] = DBManager.getMonthConsumption(Integer.parseInt(selected_year),selected_month,0);//月支出
                                    month_money[1] = DBManager.getMonthConsumption(Integer.parseInt(selected_year),selected_month,1);//月收入
                                    month_money[2] = month_money[1] - month_money[0];//月结余
                                    month_expend.setText(String.valueOf(month_money[0]));
                                    month_income.setText(String.valueOf(month_money[1]));
                                    month_balance.setText(String.valueOf(month_money[2]));
                                    chart(Integer.parseInt(selected_year),selected_month,mscv.getSelectedItem());
                                    list_data_change(Integer.parseInt(selected_year),selected_month);
                                    pieChart(Integer.parseInt(selected_year),selected_month);
                                    lineChart.highlightValue(null);
                                    adapter.notifyDataSetChanged();//更新数据
                                    MyMarkerView mv = new MyMarkerView(getContext(), R.layout.custom_marker_view,selected_year,selected_month);

                                    // Set the marker to the chart
                                    mv.setChartView(lineChart);
                                    lineChart.setMarker(mv);
                                }
                            });
                            return null;
                        }).build();
                Window window = dialog.getWindow();
                window.setGravity(Gravity.TOP);
                dialog.show();

            }
        });
    }

    public void pieChart(int year, int month){
        chart3.setUsePercentValues(true);
        chart3.getDescription().setEnabled(false);
        chart3.setExtraOffsets(5, 10, 5, 5);

        chart3.setDragDecelerationFrictionCoef(0.95f);


        chart3.setDrawHoleEnabled(true);
        chart3.setHoleColor(Color.WHITE);

        chart3.setTransparentCircleColor(Color.WHITE);
        chart3.setTransparentCircleAlpha(110);

        chart3.setHoleRadius(58f);
        chart3.setTransparentCircleRadius(61f);

        chart3.setDrawCenterText(true);

        chart3.setRotationAngle(0);
        chart3.setRotationEnabled(true);
        chart3.setHighlightPerTapEnabled(true);

        chart3.animateY(1400, Easing.EaseInOutQuad);


        // entry label styling
        chart3.setEntryLabelColor(Color.parseColor("#ff999999"));
        // chart3.setEntryLabelTypeface(tfRegular);
        chart3.setEntryLabelTextSize(0f);


        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        consumptionClasses = DBManager.getAllConsumptionClass();
        int length = consumptionClasses.size();
        ArrayList<String> class_name = new ArrayList<>();
        ArrayList<Float> class_money = new ArrayList<>();
        for (int i = 0; i < length; i ++){
            float temp = DBManager.getMonthClassConsumption(year,month,consumptionClasses.get(i));
            if (temp != 0){
                class_name.add(consumptionClasses.get(i));
                class_money.add(temp);
            }
        }
        int length2 = class_name.size();
        final String[] parties = new String[length2];
        for (int i = 0; i < length2; i ++){
            //Log.i("消费分类",consumptionClasses.get(i));
            parties[i] = class_name.get(i);
            entries.add(new PieEntry((class_money.get(i)),
                    parties[i % parties.length]));
        }


        PieDataSet dataSet = new PieDataSet(entries, "");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(Color.parseColor("#ff999999"));
        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        dataSet.setSelectionShift(5f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new MyPercentFormatter(chart3));
        data.setValueTextSize(8f);
        data.setValueTextColor(Color.parseColor("#ff999999"));
        // data.setValueTypeface(tfLight);
        chart3.setData(data);
        if (length2 == 0){
            Log.e("data","null");
            chart3.setCenterText("暂无数据");
        }else {
            chart3.setCenterText("总消费" + "\n" + String.valueOf(month_money[0]));
        }
        chart3.setNoDataText("暂无数据");

        // undo all highlights
        chart3.highlightValues(null);

        chart3.invalidate();
        chart3.setCenterTextColor(Color.parseColor("#ff999999"));


        chart3.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                PieEntry p = (PieEntry) e;
                Log.e("entry", p.getLabel());
                chart3.setCenterText(p.getLabel() + "\n" + e.getY());
            }

            @Override
            public void onNothingSelected() {
                chart3.setCenterText("总消费" + "\n" + month_money[0]);
            }
        });

    }



    public void chart(int year, int month, int kind){
        lineChart.getDescription().setEnabled(false);
        lineChart.setTouchEnabled(true);
        lineChart.setDragDecelerationFrictionCoef(0.9f);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setDrawGridBackground(false);
        lineChart.setHighlightPerDragEnabled(true);
        lineChart.setVisibleXRangeMinimum(1);

        lineChart.setPinchZoom(true);
        lineChart.animateX(0);

        Legend l = lineChart.getLegend();//图例
        l.setForm(Legend.LegendForm.LINE);
        l.setTextSize(10f);
        l.setTextColor(Color.GRAY);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularityEnabled(true);
        xAxis.setGranularity(2);
        xAxis.setSpaceMax(1f);

        xAxis.setTextSize(10f);//x轴字体大小
        xAxis.setTextColor(Color.GRAY);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        //      xAxis.setAxisMinimum(-20f);


        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setTextColor(Color.GRAY);
        //leftAxis.setAxisMaximum(200f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
        //leftAxis.setGranularity(1);
        leftAxis.setDrawAxisLine(false);//隐藏y轴左侧轴线

        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setEnabled(false); // 隐藏右侧y轴
        // 获取某年某月的月份天数 查询数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //Date someday = new Date(System.currentTimeMillis());
        int days_length = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            LocalDate today = LocalDate.of(year,month,1);
            days_length = today.lengthOfMonth();
            System.out.println("天数"+days_length);
        }
        String[] xLabels = new String[days_length];
        xAxis.setLabelCount(days_length);
        Log.i("days",String.valueOf(days_length));
        for (int i = 1; i <= days_length; i++){
            xLabels[i-1] = String.valueOf(i);
        }
        xAxis.setValueFormatter(new ValueFormatter() {   //X轴自定义标签内容
            @Override
            // index从1开始 作为数组下标-1
            public String getAxisLabel(float index, AxisBase axisBase) {
                //Log.i("下标",String.valueOf(index));
                Log.i("index",String.valueOf(index));
                if (index < 0 || index >= xLabels.length) {
                    return "";
                }
                return xLabels[(int)(index-1)];
            }
        });



        LineDataSet set;
        LineData data = new LineData();
        ArrayList<Entry> values = new ArrayList<Entry>();
            // 天数
            for (int j = 1; j <= days_length; j ++){
                float daySumComsumption = DBManager.getDaySumConsumption(year, month, j,kind);
                values.add(new Entry(j, daySumComsumption));;
            }
            set = new LineDataSet(values,null);
            set.setForm(Legend.LegendForm.NONE);
            set.setAxisDependency(YAxis.AxisDependency.LEFT);
            set.setColor(Color.parseColor("#7CB2EB"));
            set.setCircleColor(Color.BLUE);
            set.setLineWidth(1f);
            set.setCircleRadius(3f);
            set.setFillAlpha(65);
            set.setFillColor(Color.BLUE);
            //set.setHighLightColor(Color.BLUE);
            set.setDrawCircleHole(false);
            set.setDrawCircles(false);
            set.setDrawValues(false);//隐藏折线点上的数据
            set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            data.addDataSet(set);
            set.setHighLightColor(Color.TRANSPARENT);

        data.setValueTextColor(Color.GRAY);
        data.setValueTextSize(9f);


        lineChart.setData(data);
        MyMarkerView mv = new MyMarkerView(getContext(), R.layout.custom_marker_view,selected_year,selected_month);

        // Set the marker to the chart
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
    }

    public void bindData(){
        // 获取当前月份的下标
        Calendar calendar = Calendar.getInstance();
        int currentMonth = calendar.get(Calendar.MONTH);
        for (int i = 0; i < months.length; i++){
            months[i] = String.valueOf(i+1) + "月";
        }
        // tab显示1-12月
        for (int i = 0; i < months.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText(months[i]));
        }
        // 默认选中当前月份的下标
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                //tabLayout.smoothScrollTo(tablayoutOffsetWidth,0);
                tabLayout.getTabAt(currentMonth).select();
//                if (currentMonth == 5) {
//                    month_balance.setText("455");
//                }
            }
        });

        // 当前月份之后的月份设置为不可选

    }

    // 支出/收入切换开关
    public void switchChange(){
        List<SegmentedControlItem> filesType = createFilesType();
        mscv.addItems(filesType);
        mscv.setSelectedItem(0);//默认为第一项支出

        mscv.setOnSegItemClickListener(new SegmentedControlView.OnSegItemClickListener() {
            @Override
            public void onItemClick(SegmentedControlItem item, int position) {
                int cur_year = Integer.parseInt((String) year_btn.getText());
                int cur_month = tabLayout.getSelectedTabPosition() + 1;
                chart(cur_year,cur_month,position);
                lineChart.highlightValue(null);

            }
        });
    }

    private List<SegmentedControlItem> createFilesType(){
        List<SegmentedControlItem> items = new ArrayList<>();
        items.add(new SegmentedControlItem(getResources().getString(R.string.expenses)));
        items.add(new SegmentedControlItem(getResources().getString(R.string.income)));
        return items;
    }



    // 获取某年某月的天数
    public static int getDaysOfMonth(int year, int month) {
        Calendar a = Calendar.getInstance();//获取当前时间
        a.set(Calendar.YEAR, year );
        a.set(Calendar.MONTH, month-1);// Calendar月份是以0开始的 所以要-1
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int days_count= a.get(Calendar.DATE);
        return days_count;
    }


}

